package com.knightboy.smartshoes.myUi;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.knightboy.smartshoes.coreUtil.SenserData;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 在一个BLE设备上管理和GATT服务器连接，和数据交互
 */
public class BlueToothLeService extends Service {
    //测试标签
    private final static String TAG = "test";

    //
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;
    private ArrayList<byte[]> mRecvDataArrayList;
    private int mConnectionState = STATE_DISCONNECTED;

    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_CONNECTING = 1;
    public static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";

    public final static UUID UUID_XIANGMA_SERIAL_PORT_SERVICE =
            UUID.fromString("0000ffe0-0000-1000-8000-00805F9B34FB");
    public final static UUID UUID_XIANGMA_SERIAL_PORT_CHAR =
            UUID.fromString("0000ffe1-0000-1000-8000-00805F9B34FB");

    private BluetoothGattCharacteristic mSerialDataChar = null;

    //定义BluetoothGattCallBack对象
    //为了对BluetoothGatt返回结果做某些操作
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        /**
         * 读取到RSSI是返回调用
         * @param gatt
         * @param rssi
         * @param status
         */
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            SenserData.setRssi(rssi);
            if(rssi < -85){
                broadcastUpdate("com.knightboy.rssi");
            }
        }

        /**
         * 连接状态改变时调用
         * @param gatt
         * @param status
         * @param newState
         */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                mSerialDataChar = null;
                if(mBluetoothGatt!=null)
                {
                    mBluetoothGatt.close();
                    mBluetoothGatt = null;
                }
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        /**
         * 服务找到时调用
         * @param gatt
         * @param status
         */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> gattServices = getSupportedGattServices();
                for (BluetoothGattService gattService : gattServices) {
                    if(UUID_XIANGMA_SERIAL_PORT_SERVICE.equals(gattService.getUuid()))
                    {
                        mSerialDataChar = gattService.getCharacteristic(UUID_XIANGMA_SERIAL_PORT_CHAR);
                        if(mSerialDataChar != null)
                        {
                            setCharacteristicNotification(mSerialDataChar, true);
                        }
                        mConnectionState = STATE_CONNECTED;
                        broadcastUpdate(ACTION_GATT_CONNECTED);
                    }
                }
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        /**
         * 获得读取的数据，加入到ArrayList<byte[]>的列表中,并广播出结果
         * @param gatt
         * @param characteristic
         * @param status
         */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                mRecvDataArrayList.add(characteristic.getValue());
                broadcastUpdate(ACTION_DATA_AVAILABLE);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
        {

        }

        /**
         * 读取的数据发生变化时调用，也要将数据存入到列表中。就是在这里获得了所有数据
         * @param gatt
         * @param characteristic
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            mRecvDataArrayList.add(characteristic.getValue());
//            Log.e(TAG,characteristic.getValue().length + "");
            //传感器数据准备好之后发送广播
            broadcastUpdate(ACTION_DATA_AVAILABLE);
        }
    };

    /**
     * 根据指定动作发送广播
     * @param action
     */
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        BlueToothLeService getService() {
            return BlueToothLeService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mRecvDataArrayList = new ArrayList<byte[]>();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /**
     * 关闭服务
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * 初始化程序 ，获得BluetoothAdapter通过BluetoothManager
     * @return
     */
    public boolean initialize() {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * 返回现在连接状态
     * @return
     */
    public synchronized int getState() {
        return mConnectionState;
    }

    /**
     * 返回收到的数据列表
     * @return
     */
    public synchronized ArrayList<byte[]> getRecvedData() {
        return mRecvDataArrayList;
    }

    /**
     * 连接BLE设备上的Gatt服务器
     * @param address 蓝牙设备地址
     * @return 连接成功返回真。连接结果由BluetoothGattCallback#onConnectionStateChange（）异步返回。
     */
    public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }


        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }

        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        //改变连接状态
        mConnectionState = STATE_CONNECTING;
        return true;
    }

    /**
     * 断开连接，连接结果由BluetoothGattCallback#onConnectionStateChange（）异步返回。
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * 使用BLE设备之后，调用该方法关闭相应资源
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.disconnect();
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * 从BluetoothGattCharacteristic读取数据. 读取结果由
     * BluetoothGattCallback#onCharacteristicRead（）返回报告
     * @param characteristic 数据读取源
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * 向蓝牙设备写字节数组数据
     * @param out
     * @return
     */
    public boolean write(byte[] out) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null || mSerialDataChar == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }
        mSerialDataChar.setValue(out);
        return mBluetoothGatt.writeCharacteristic(mSerialDataChar);
    }

    /**
     * @param characteristic 通知数据
     * @param enabled 使能
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    }

    /**
     * 得到支持的GATT服务列表，在BluetoothGatt#discoverServices()之后调用
     * @return
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices();
    }

    /**
     * 读取rssi,在onReadRssi中返回
     * @return
     */
    public boolean readRemoteRssi(){
        if(mBluetoothGatt.readRemoteRssi()){
            return true;
        }
        return false;
    }
}